import { Component, OnInit } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import AppApi from '../../api/index'
import UserBriefInfoVO from '../../common/vo/user-brief-info'
import MenuTreeVO from 'src/app/common/vo/menu-tree'
import { AppRouterService } from '../../service/app-router.service'
import { AppStateService } from '../../service/app-state.service'
import { AppScreenService } from '../../service/app-screen.service'

@Component({
  selector: 'SideNav',
  templateUrl: './side-nav.component.html',
  styleUrls: ['./side-nav.component.less']
})
export class SideNavComponent implements OnInit {
  defaultAvatar = '../../../assets/img/league-badge.png'
  private loading = false
  private _userBriefInfo: UserBriefInfoVO
  private _rootMenu: MenuTreeVO


  constructor(
    private httpClient: HttpClient,
    public routerService: AppRouterService,
    public stateService: AppStateService,
    public screenService: AppScreenService
  ) {
    this.userBriefInfo = new UserBriefInfoVO({})
    this.rootMenu = new MenuTreeVO()
  }

  ngOnInit(): void {
    this.loading = true
    this.updateUserBriefInfo()
    this.updateMenuTree()
  }

  menuClickHandle($clickEvent: MouseEvent, menu: MenuTreeVO): void {
    if (!menu.url) return
    const dest = menu.url.substring(1)
    this.stateService.activedMenu = menu.name
    this.routerService.navigate(['home', {
      outlets: { mainPanel: dest }
    }])
  }

  public updateUserBriefInfo() {
    this.httpClient
      .post<UserBriefInfoVO>(AppApi.UserApi.brief, {})
      .subscribe(userInfo => {
        if (!userInfo.avatar) { userInfo.avatar = this.defaultAvatar }
        this.userBriefInfo = userInfo
      })
  }
  public updateMenuTree() {
    this.httpClient.post<MenuTreeVO>(AppApi.UserApi.myMenus, {})
      .subscribe(menuTree => {
        this.rootMenu = menuTree
      })
  }

  public get userBriefInfo(): UserBriefInfoVO {
    return this._userBriefInfo
  }
  public set userBriefInfo(value: UserBriefInfoVO) {
    this._userBriefInfo = value
  }
  public get rootMenu(): MenuTreeVO {
    return this._rootMenu
  }
  public set rootMenu(value: MenuTreeVO) {
    this._rootMenu = value
  }
}
